<template>
  <div style="height: 100%">
    <a-spin :spinning="isTableLoading" wrapperClassName="spinning-container">
      <div class="header-container" ref="headerContainer">
        <page-header :title="l('Roles')"></page-header>
        <a-card :bordered="false">
          <a-form :layout="'vertical'" @submit.prevent="getSearchData">
            <a-row :gutter="8">
              <!-- 搜索 -->
              <a-col :sm="12">
                <a-form-item>
                  <a-input-search
                    name="filterText"
                    :placeholder="l('SearchWithThreeDot')"
                    @search="getSearchData"
                    enterButton
                    v-model:value="filterText"
                  />
                </a-form-item>
              </a-col>
              <!-- 权限过滤 -->
              <a-col :sm="12">
                <a-form-item>
                  <permission-combox
                    :multiple="true"
                    :dropDownStyle="{ 'max-height': '500px' }"
                    :selectedPermission="selectedPermission"
                    @selectedPermissionChange="selectPermissionChange($event)"
                  >
                  </permission-combox>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
          <!-- 操作部分 -->
          <a-row :gutter="8">
            <a-col :md="20" :sm="12">
              <a-button
                :type="'primary'"
                v-if="isGranted('Pages.Administration.Roles.Create')"
                @click="createOrEdit"
              >
                <plus-outlined />
                <span>{{ l('CreateNewRole') }}</span>
              </a-button>
              <a-button
                :type="'danger'"
                v-if="isGranted('Pages.Administration.Roles.Delete')"
                @click="batchDelete()"
              >
                <delete-outlined />
                <span>{{ l('BatchDelete') }}</span>
              </a-button>
            </a-col>
          </a-row>

          <!-- 数据部分 -->
          <div class="my-md">
            <a-alert :type="'info'" :showIcon="true">
              <template #message>
                <span v-html="l('GridSelectedXItemsTips', selectedRowKeys.length)"></span>
                <a @click="restCheckStatus()" class="ml-md">{{ l('ClearEmpty') }}</a>
                <a-divider type="vertical"></a-divider>
                <a @click="refresh()">{{ l('Refresh') }}</a>
              </template>
            </a-alert>
          </div>
        </a-card>
      </div>
      <!-- 表格 -->
      <div class="table-container">
        <a-table
          size="middle"
          :scroll="{ x: tableWidthScroll, y: tableHeightScroll }"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data-source="dataList"
          :pagination="{
            total: totalItems,
            current: pageNumber,
            pageSize: pageSize,
            showTotal: showTotalInfo,
            showQuickJumper: true,
            showSizeChanger: true,
            change: pageNumberChange,
            showSizeChange: pageNumberChange,
            pageSizeOptions: pageSizeOptions,
            size: 'middle',
          }"
          :rowSelection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
            getCheckboxProps: getCheckboxProps,
            checkAll: checkAll,
          }"
          @change="tableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'displayName'">
              <span>{{ record.displayName }}</span>
              <a-tag v-if="record.isStatic" color="#108ee9"> {{ l('Static') }}</a-tag>
              <a-tag v-if="record.isDefault" color="#2db7f5"> {{ l('Default') }}</a-tag>
            </template>
            <template v-if="column.key === 'creationTime'">
              {{ _moment(record.creationTime) }}
            </template>
            <template v-if="column.key === 'actions'">
              <a
                class="table-edit"
                @click="createOrEdit(record)"
                v-if="isGranted('Pages.Administration.Roles.Edit')"
              >
                <edit-outlined />
                {{ l('Edit') }}
              </a>
              <!-- 删除 -->
              <a-popconfirm
                placement="top"
                v-if="
                  !record.isStatic &&
                  isGranted('Pages.Administration.Roles.Delete') &&
                  record.name !== 'Admin'
                "
                :okText="l('Ok')"
                :cancelText="l('Cancel')"
                @confirm="deleteItem(record)"
              >
                <template #title>
                  {{ l('ConfirmDeleteWarningMessage') }}
                </template>
                <a class="table-delete"> <delete-outlined />{{ l('Delete') }} </a>
              </a-popconfirm>
            </template>
          </template>
        </a-table>
      </div>
    </a-spin>
  </div>
</template>

<script lang="ts">
  import { PagedListingComponentBase } from '/@/shared/component-base';
  import { PermissionCombox } from '/@/app/admin-shared';
  import { RoleListDto, RoleServiceProxy } from '/@/shared/service-proxies';
  import CreateEditRoleCompent from './create-or-edit-role/create-or-edit-role.vue';
  import { defineComponent } from 'vue';
  import _ from 'lodash';
  import { AppConsts } from '/@/abpPro/AppConsts';
  import { PlusOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons-vue';
  import { IPagedRequestDto } from '/@/shared/component-base/interfaces';
  import { ColumnType } from 'ant-design-vue/lib/table';

  export default defineComponent({
    name: 'roles',
    components: {
      PermissionCombox,
      CreateEditRoleCompent,
      PlusOutlined,
      DeleteOutlined,
      EditOutlined,
    },
    mixins: [PagedListingComponentBase],
    data() {
      return {
        roleServiceProxy: new RoleServiceProxy(),
        // 选中的权限过滤
        selectedPermission: [] as any,

        // 请求参数
        filterText: undefined,
        dataList: [] as RoleListDto[],
      };
    },
    methods: {
      /**
       * 获取数据
       */
      fetchDataList(request: IPagedRequestDto, finishedCallback?: () => void) {
        this.roleServiceProxy
          .getPaged(
            this.selectedPermission,
            null,
            null,
            this.filterText,
            request.sorting,
            request.maxResultCount,
            request.skipCount,
          )
          .finally(() => {
            finishedCallback!();
          })
          .then((res) => {
            this.showPaging(res);
          });
      },
      /**
       * table默认配置 （是否禁用）
       */
      getCheckboxProps(record) {
        return {
          disabled: record.displayName == 'Admin',
          name: record.displayName,
        };
      },
      getColumns(): ColumnType<RoleListDto>[] {
        return [
          {
            title: 'No',
            customRender: ({ index }) => {
              const a = (this.pageNumber - 1) * this.pageSize + (index + 1);
              return a;
            },
            width: 60,
            fixed: 'left',
          },
          {
            title: this.l('RoleName'),
            dataIndex: 'displayName',
            key: 'displayName',
            ellipsis: true,
          },
          {
            title: this.l('CreationTime'),
            dataIndex: 'creationTime',
            key: 'creationTime',
            ellipsis: true,
            sorter: {
              multiple: 0,
            },
          },
          {
            title: this.l('Actions'),
            dataIndex: 'actions',
            key: 'actions',
            width: 250,
            align: 'center',
            ellipsis: true,
            fixed: 'right',
          },
        ];
      },
      /**
       * 添加角色  修改角色
       */
      createOrEdit(item?: RoleListDto) {
        this.modalHelper
          .create(
            CreateEditRoleCompent,
            { id: item.id ?? null, displayName: item.displayName ?? null },
            {
              width: '400px',
            },
          )
          .subscribe((res) => {
            if (res) {
              this.refresh();
            }
          });
      },
      /**
       * 批量删除
       */
      batchDelete() {
        const selectCount = this.selectedRowKeys.length;
        if (selectCount <= 0) {
          this.message.warn(this.l('PleaseSelectAtLeastOneItem'));
          return;
        }
        this.message.confirm(
          this.l('ConfirmDeleteXItemsWarningMessage', selectCount),
          '',
          (res) => {
            if (res) {
              const ids = _.map(this.selectedRowKeys);
              this.isTableLoading = true;
              this.roleServiceProxy
                .batchDelete(ids)
                .finally(() => {
                  this.isTableLoading = false;
                })
                .then(() => {
                  this.selectedRowKeys = [];
                  this.selectPermissionChange(this.selectedPermission);
                  this.notify.success(this.l('SavedSuccessfully'));
                });
            }
          },
        );
      },
      /**
       * 单个删除
       */
      deleteItem(item: RoleListDto) {
        if (item.isStatic) {
          this.message.warn(
            this.l('XUserCannotBeDeleted', AppConsts.userManagement.defaultAdminUserName),
          );

          return;
        }
        this.isTableLoading = true;
        this.roleServiceProxy
          .delete(item.id)
          .finally(() => {
            this.isTableLoading = false;
          })
          .then(() => {
            this.selectPermissionChange(this.selectedPermission);
            this.notify.success(this.l('SuccessfullyDeleted'));
          });
      },
      /** 选中的权限发生改变 */
      selectPermissionChange(permissions: string[]) {
        this.selectedPermission = permissions;
        this.refreshGoFirstPage();
      },
    },
  });
</script>

<style scoped lang="less">
  @import './roles.less';
</style>
